<template>
  <el-dialog
    :title="title"
    :visible.sync="visible"
    width="35%"
    top="10vh"
    :before-close="closeDialogHandle"
    :close-on-click-modal="false"
  >
    <el-form size="small" :model="game" :rules="gameRules" ref="gameForm" @keyup.enter.native="submitHandle" label-width="85px">
      <el-form-item label="游戏名称" prop="gameName">
        <el-input v-model="game.gameName" clearable placeholder="请输入游戏名称" class="width95percent"></el-input>
      </el-form-item>
      <el-form-item label="开始时间" prop="startTime">
        <el-date-picker
          v-model="game.startTime"
          type="datetime"
          placeholder="请选择开始时间"
          default-time="00:00:00"
          value-format="timestamp"
          :picker-options="pickerOptions"
          class="width95percent">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="结束时间" prop="endTime">
        <el-date-picker
          v-model="game.endTime"
          type="datetime"
          placeholder="请选择结束时间"
          default-time="23:59:59"
          value-format="timestamp"
          :picker-options="pickerOptions"
          class="width95percent">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input
          type="textarea"
          placeholder="请输入备注"
          v-model="game.remark"
          maxlength="250"
          show-word-limit
          resize="none"
          class="width95percent"
        />
      </el-form-item>
    </el-form>
    <span slot="footer">
      <el-button @click="closeDialogHandle(false)">取 消</el-button>
      <el-button v-show="!optType" :disabled="buttonLoad" type="primary" @click="saveHandle">添 加</el-button>
      <el-button v-show="optType" :disabled="buttonLoad" type="primary"  @click="updateHandle">修 改</el-button>
    </span>
  </el-dialog>
</template>

<script>
  export default {
    data() {
      return {
        // 弹出框显示状态[true-显示 false-隐藏]
        visible: false,
        // 弹出框标题
        title: undefined,
        // 操作类型[true-修改 false-添加]
        optType: false,
        // 游戏对象
        game: {
          // 主键
          id: undefined,
          // 游戏名称
          gameName: '',
          // 开始时间
          startTime: '',
          // 结束时间
          endTime: '',
          // 备注
          remark: '',
        },
        // 游戏表单校验规则对象
        gameRules: {
          gameName: [
            { required: true, message: '请输入游戏名称', trigger: 'blur' }
          ],
          startTime: [
            { required: true, message: '请选择开始时间', trigger: 'change' }
          ],
          endTime: [
            { required: true, message: '请选择结束时间', trigger: 'change' }
          ],
        },
        // 按钮禁用状态[true-禁用 false-可用]
        buttonLoad: false,
        // 日期组件选项禁用配置对象
        pickerOptions: {
          /**
           * 选项禁用判断规则方法
           * @param date 日期对象
           * @return {boolean} true-禁用 false-正常
           */
          disabledDate: (date) => {
            if (this.optType) {
              let startTime = Math.min(this.game.startTime, Date.now());
              let num = startTime % 2 === 0 ? 1 : 0;
              return date.getTime() < startTime - 8.64e7 + num;
            } else {
              return date.getTime() < Date.now() - 8.64e7;
            }
          }
        }
      }
    },
    methods: {
      /**
       * 初始化弹出框方法
       * @param {Object} game 游戏对象
       */
      initDialog(game) {
        // console.log('game', game);
        // 打开弹出框
        this.visible = true;

        if (game) {
          this.title = '游戏修改';
          this.optType = true;

          this.$nextTick(() => {
            let _game = this.game;
            for (let propKey in _game) {
              if (game.hasOwnProperty(propKey)) {
                _game[propKey] = game[propKey];
              }
            }
            _game.startTime = Date.parse(_game.startTime);
            _game.endTime = Date.parse(_game.endTime);
          });
        } else {
          this.title = '添加游戏';
          this.optType = false;
        }
      },
      /**
       * 表单提交事件
       */
      submitHandle() {
        if (this.optType) {
          this.updateHandle();
        } else {
          this.saveHandle();
        }
      },
      /**
       * 保存游戏事件
       */
      saveHandle() {
        this.$refs.gameForm.validate((valid) => {
          if (!valid) {
            return false;
          }
          if (this.game.startTime > this.game.endTime) {
            this.notify('', '温馨提示', '游戏开始时间不能大于结束时间');
            return false;
          }
          // 按钮禁用
          this.buttonLoad = true;
          this.$axios.$post('/game/save', this.game)
            .then(() => {
              this.notify('success', '操作成功', `‘${this.game.gameName}’游戏添加成功`);

              this.closeDialogHandle(true);
            })
            .catch(() => {})
            .finally(() => {
              // 按钮恢复可使用
              this.buttonLoad = false;
            })
        });
      },
      /**
       * 修改游戏事件
       */
      updateHandle() {
        this.$refs.gameForm.validate((valid) => {
          if (!valid) {
            return false;
          }
          if (this.game.startTime > this.game.endTime) {
            this.notify('', '温馨提示', '游戏开始时间不能大于结束时间');
            return false;
          }
          // 按钮禁用
          this.buttonLoad = true;
          this.$axios.$post('/game/update', this.game)
            .then(() => {
              this.notify('success', '操作成功', `修改‘${this.game.gameName}’游戏成功`);

              this.closeDialogHandle(true);
            })
            .catch(() => {})
            .finally(() => {
              // 按钮恢复可使用
              this.buttonLoad = false;
            })
        });
      },
      /**
       * 关闭弹出框方法
       * @param {boolean | function} refresh 是否刷新父级组件数据
       */
      closeDialogHandle(refresh) {
        // 重置表单
        this.$refs.gameForm.resetFields();
        this.game.id = undefined;

        if (typeof refresh === 'function') {
          refresh = false;
        }
        if (refresh) {
          // 向上传递事件
          this.$emit('refresh-table');
        }
        this.$nextTick(() => {
          // 关闭弹出框
          this.visible = false;
        });
      },
      /**
       * 日期组件选项禁用逻辑方法
       * @param date 选项日期对象
       */
      disabledDate(date) {
        if (this.optType) {
          let time = Math.min(this.game.startTime, Date.now());
          // 解决时间为：xx:xx:xx 00:00:00 时产生的阈值问题
          let num = time % 2 === 0 ? 1 : 0;
          // 小于该时间戳则禁用
          return date.getTime() < time - 8.64e7 + num;
        } else {
          // 小于该时间戳则禁用
          return date.getTime() < Date.now() - 8.64e7;
        }
      }
    },
  }
</script>

<style scoped>
  .width95percent {
    width: 95%;
  }
</style>
